import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'
import context from './context'
import './App.css'
export default class App extends Component {
  state = {
    todos: JSON.parse(localStorage.getItem('todos')) || [],
    editId: undefined,
  }
  render() {
    const { todos, editId } = this.state
    return (
      <context.Provider value={editId}>
        <div className="todo-container">
          <div className="todo-wrap">
            <Header></Header>
            <div>
              <List todos={todos}></List>
              <Footer></Footer>
            </div>
          </div>
        </div>
      </context.Provider>
    )
  }

  componentDidMount() {
    // 订阅话题,添加任务名
    this.addId = PubSub.subscribe('add', (topic, todoName) => {
      // 根据任务名创建任务对象
      const obj = {
        id: Date.now(),
        todoName,
        isDone: false,
      }

      this.state.todos.push(obj)

      this.setState({
        todos: this.state.todos,
      })
    })

    // 订阅话题,修改editId
    this.sEI = PubSub.subscribe('setEditId', (topic, id) => {
      this.setState({
        editId: id,
      })
    })

    // 订阅话题,修改指定任务对象的任务名
    this.sTN = PubSub.subscribe('setTodoName', (topic, { id, tN }) => {
      this.state.todos.forEach((item) => {
        if (item.id === id) item.todoName = tN
      })
      this.setState({
        editId: undefined,
        todos: this.state.todos,
      })
    })
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.addId)
    PubSub.unsubscribe(this.sEI)
  }

  // 每次修改数据,都应该将最新数据存储到本地缓存中.之前在render中写,写的过程中,会不断重新编译,重新执行所有代码.render在组件挂载的时候也会执行,会将错误的代码存储到本地缓存中. 但是如果使用componentDidUpdate,在写的过程中这个钩子不会触发,就不会往本地缓存中存储错误的数据
  componentDidUpdate() {
    localStorage.setItem('todos', JSON.stringify(this.state.todos))
  }
}
